# encoding:utf8
'''
package manager base for plugin|runner
'''
import os
import sys
import shutil
import logging


def path_comp(tpath):
    return tpath.replace("/", os.sep)


def temp_path():
    TEMP_PATH_NAME = "TEMPLATE_REL_PATH"
    if os.path.isdir(TEMP_PATH_NAME):
        shutil.rmtree(TEMP_PATH_NAME)
    os.mkdir(TEMP_PATH_NAME)
    return TEMP_PATH_NAME


def pack_file(temppath):
    cmd_str = "sudo make"
    os.system(cmd_str)
    shutil.copy("ccpm", temppath)
    shutil.copy("makefile", temppath)
    shutil.copytree("static", os.path.join(temppath, "static"))


def luac_conf(temppath):
    conf_file = "./%s/static/gluaconf" % temppath
    os.system("../bin/luac5.3 -o %s %s " % (conf_file, conf_file))


def chk_verstr(verstr):
    if not verstr.startswith("v"):
        return False
    vlist = verstr[1:].split(".")
    for vnum in vlist:
        if int(vnum) >= 10:
            return False
    return True


if __name__ == "__main__":

    if len(sys.argv) == 1:
        logging.error("must input ver fmt like vx.x.x")
        sys.exit(1)

    verstr = sys.argv[1]
    chk_verstr(verstr)

    PROJ_PATH = os.path.abspath(path_comp("./../src"))
    os.chdir(PROJ_PATH)

    path_temp = temp_path()
    pack_file(path_temp)
    luac_conf(path_temp)
    shutil.make_archive("ccpm_%s" % verstr, "zip", root_dir=path_temp)
    shutil.rmtree(path_temp)
